import React, {Component} from 'react';
import {
    View,
    Text,
    TextInput,
    Button,
    StyleSheet,
    ScrollView,
    Image,
    TouchableOpacity,
    ImageBackground,
    ToastAndroid,
    DeviceEventEmitter, Modal,
} from 'react-native';
import * as ImagePicker from 'react-native-image-picker';
import AntIcon from 'react-native-vector-icons/AntDesign';
import Loading from '../../compenent/Loading';
import {DOMAIN_URL, addEvent, eventUpdate, uploadFile, honorAdd, honorReview, getUserInfoList} from '../../../util/api';
import {DateTimePickerAndroid} from '@react-native-community/datetimepicker';
import moment, {months} from 'moment';
import {PAGENAME} from '../../../util/PageName';
import {style} from '../../../theme';
import AsyncStorage from "@react-native-async-storage/async-storage";
import {List} from "react-native-paper";
import Icon from 'react-native-vector-icons/MaterialIcons';


class PunishmentScreen extends Component {
    honorid: string;
    constructor(props) {
        super(props);
        this.honorid = this.generateUUIDFallback();
        this.UserInfoList();
        console.log(this.generateUUIDFallback());
        console.log(props.route.params);
        console.log(props.route.params?.data);
        this.state = {
            honerid: this.generateUUIDFallback(),
            data: props.route.params?.data,
            name: props.route.params?.data.name || '',
            description: props.route.params?.data.description || '',
            userId: '',
            score: `${props.route.params?.data.score || 0}`,
            images: [],
            preImages: props.route.params?.data.imageDetails || [],
            endTime: moment(props.route.params?.data.endTime).toDate() || new Date(),
            userList: [],
            modalVisibleDept: false,
            isAdmin: false,
            // 'descriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescription',
            // score: '2',
            // images: [],
            // endTime: new Date(),
            loading: false,
        };
        AsyncStorage.getItem('isAdmin').then(value => {
            console.log('this.state.isAdmin', value);
            this.setState({
                isAdmin: value == 'true' ? true : false,
            });
        });
    }

    generateUUIDFallback() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    UserInfoList() {
        // 这里是你想要在A页面被重新聚焦时执行的方法
        //当页面重新获得焦点时，执行这个方法
        getUserInfoList(null).then((res) => {
            this.setState({userList: res.rows});
        });
    };

    pickImage = () => {
        ImagePicker.launchImageLibrary(
            {mediaType: 'photo', selectionLimit: 1},
            response => {
                if (!response.didCancel) {
                    this.setState(prevState => ({
                        images: [
                            ...new Set([
                                ...prevState.images,
                                ...(response.assets.map(asset => asset) || []),
                            ]),
                        ],
                    }));
                }
            },
        );
    };
    submitData = async () => {

        // setTimeout(() => {
        //   this.setState({ loading: false })
        if (!this.state.name) {
            ToastAndroid.show('请填写标题。', 2000);
            return;
        }
        if (Number.parseInt(this.state.score, 10) <= 0) {
            ToastAndroid.show('惩罚分数必须大于0。', 2000);
            return;
        }
        if (!this.state.description) {
            ToastAndroid.show('请填写描述。', 2000);
            return;
        }
        if (!this.state.userId) {
            ToastAndroid.show('请选择惩罚用户。', 2000);
            return;
        }

        let imgs: any[] = this.state.preImages.map(v => v.id);
        if (!this.state.images || this.state.images.length === 0) {
            ToastAndroid.show('请上传图片。', 2000);
            return;
        }
        console.log(this.state.images);
        this.setState({loading: true});

        // }, 5000);
        for (let index = 0; index < this.state.images.length; index++) {
            const element = this.state.images[index];
            await uploadFile(
                {
                    uri: element.uri, // 替换为实际文件路径
                    type: element.type,
                    name: element.fileName,
                },
                'image',
            )
                .then(res => {
                    console.log(res);
                    if (res.code == 0) {
                        console.log(`${element} upload success.`);
                        imgs.push(res.data.id);
                    } else {
                        ToastAndroid.show(`上传失败:${res.msg}`, 2000);
                    }
                })
                .catch(e => {
                    console.log(e);
                    ToastAndroid.show(`上传失败:${e}`, 2000);
                });
        }
        // this.setState({loading: false});
        if (imgs.length > 0) {
            const data = {
                honorTitle: this.state.name,
                honorcontent: this.state.description,
                honorpic: imgs[0],
                honorscore: 0 - Number.parseInt(this.state.score, 10),
                honorid: this.honorid,
                applyuserid: this.state.userId
            };
            honorAdd(data).then(res => {
                console.log('honorAdd', res);
                if (res.code == 0) {
                    const data1 = {
                        ids: this.honorid,
                        status: '0'
                    }
                    console.log(data1);
                    honorReview(data1).then(reviewRes => {
                        console.log('honorAdd', reviewRes);
                        ToastAndroid.show(`执行成功:${res.msg}`, 3000);
                        this.props.navigation.goBack({refresh: true});
                    });
                } else {
                    ToastAndroid.show(`更新失败:${res.msg}`, 3000);
                    this.props.navigation.goBack({refresh: true});
                }
                return;
            }).catch(e => {
                this.props.navigation.goBack({refresh: true});
                // DeviceEventEmitter.emit(PAGENAME.ACTIVE_DETAIL, { name: 'back' });

            })
                .finally(() => {
                    this.setState({loading: false});
                });
        } else {
            this.setState({loading: false});
        }
    };
    inputEndTime = (event, value) => {
        this.setState({endTime: value});
    };

    render() {
        const {name, description, score, images, preImages, endTime, userId} = this.state;
        return (
            // <ImageBackground
            //   source={require('../../../assets/images/bg.jpg')} // 替换为您自己的背景图路径
            //   style={{flex: 1}}
            //   imageStyle={{opacity: 0.4}} // 修改透明度，范围为0（完全透明）到1（完全不透明）
            // >
            <View>
                <Loading loading={this.state.loading}/>
                <ScrollView contentContainerStyle={styles.container}>
                    <Text style={style.subTitle}>标题</Text>
                    <TextInput
                        style={styles.input}
                        value={name}
                        onChangeText={text => this.setState({name: text})}
                    />

                    <View style={styles.userRow}>
                        <Text style={styles.label}>惩罚用户</Text>
                        <View style={{ position: 'relative'}}>
                            <TextInput
                                style={style.inputArea}
                                value={userId}
                                onChangeText={text => {
                                    this.setState({
                                        userId: user.loginName
                                    })
                                }}
                            />
                            {this.state.userList.length > 0 && <TouchableOpacity
                                style={{
                                    position: 'absolute',
                                    top: 8,
                                    right: 8,
                                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                                    width: 30,
                                    height: 30,
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                }}
                                onPress={() => {
                                    // this.pickerRef.current.focus();
                                    this.setState({
                                        modalVisibleDept: true
                                    })
                                }}>
                                <Icon name={'expand-more'} size={18} color={'white'} />

                            </TouchableOpacity>}
                            <Modal
                                // animationType="slide"
                                transparent={true}
                                // style={{ width: 100 ,}}
                                visible={this.state.modalVisibleDept}
                                onRequestClose={() => {
                                    this.setState({
                                        modalVisibleDept: !this.state.modalVisibleDept
                                    })
                                }}
                            >
                                <View style={styles.centeredView}>
                                    <View style={styles.modalView}>
                                        <List.Section>
                                            <List.Subheader>{'                 请选择                   '}</List.Subheader>
                                            {this.state.userList.map((v, i) => {
                                                return <List.Item title={v.userName} onPress={() => {
                                                    this.setState({ userId: v.loginName })
                                                    this.setState({
                                                        modalVisibleDept: !this.state.modalVisibleDept
                                                    })
                                                }} left={props => <List.Icon {...props} icon="circle-small" />} />
                                            })}
                                        </List.Section>
                                        <View>
                                            <Button title='取消' onPress={() => {
                                                this.setState({
                                                    modalVisibleDept: !this.state.modalVisibleDept
                                                })
                                            }} />
                                        </View>
                                    </View>
                                </View>
                            </Modal>

                        </View>
                    </View>
                    <Text style={style.subTitle}>惩罚分数</Text>
                    <TextInput
                        style={styles.input}
                        value={score}
                        onChangeText={text => this.setState({score: text})}
                    />
                    <Text style={style.subTitle}>描述内容</Text>
                    <TextInput
                        style={[styles.input]}
                        value={description}
                        onChangeText={text => this.setState({description: text})}
                        multiline
                    />
                    <View style={{flexDirection: 'row'}}>
                        <Text style={style.subTitle}>图片</Text>
                    </View>
                    <View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
                        {images.map((image, index) => (
                            <View key={index} style={{position: 'relative', margin: 4}}>
                                <Image source={{uri: image.uri}} style={styles.image}/>
                                <TouchableOpacity
                                    style={{
                                        position: 'absolute',
                                        top: 2,
                                        right: 2,
                                        backgroundColor: 'rgba(0, 0, 0, 0.5)',
                                        width: 30,
                                        height: 30,
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                    }}
                                    onPress={() => {
                                        const updatedImages = images.filter(
                                            (value, idx) => idx !== index,
                                        );
                                        this.setState({images: updatedImages});
                                    }}>
                                    <Text
                                        style={{
                                            color: 'white',
                                            fontSize: 16,
                                        }}>
                                        X
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        ))}
                        {(images == null || images.length === 0) && (
                            <TouchableOpacity
                                style={{
                                    width: 75,
                                    height: 75,
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    borderWidth: 1,
                                    borderColor: 'gray',
                                    position: 'relative',
                                    margin: 4,
                                }}
                                onPress={() => {
                                    this.pickImage();
                                }}>
                                <AntIcon
                                    name={'plus'}
                                    size={50}
                                    color={'rgba(0, 0, 0, 0.3)'}
                                    style={{width: 50, height: 50}}
                                />
                            </TouchableOpacity>
                        )}

                    </View>
                    <View style={{flexDirection: 'row', alignSelf: 'center', marginVertical: 15}}>
                        <View
                            style={style.pageButton}>
                            <Button title="提交" onPress={() => this.submitData()}/>
                        </View>
                    </View>
                </ScrollView>
                {/* </ImageBackground> */}
            </View>

        );
    }
}

const styles = StyleSheet.create({
    container: {
        padding: 20,
    },
    label: {
        fontSize: 16,
        marginBottom: 5,
        fontWeight: 'bold',
    },
    input: {
        borderWidth: 1,
        borderColor: 'gray',
        borderRadius: 5,
        marginBottom: 10,
        padding: 10,
    },
    button: {
        fontSize: 16,
        color: 'blue',
        marginBottom: 10,
    },
    image: {
        width: 75,
        height: 75,
        marginBottom: 10,
    },
    userRow: {
        // flexDirection: 'row',
        margin: 4
    },
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 22
    },
    modalView: {
        margin: 20,
        backgroundColor: "white",
        borderRadius: 4,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    }
});

export default PunishmentScreen;
